<template>
  <DDeiEditorView ref="editorViewer" v-if="loadMode == 1 || loadMode == 2" :options="options" id="editor_1"></DDeiEditorView>
   <div v-if="loadMode == 3" class="ddei_sslink_outtime">
    <div class="content">
      <div class="header">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-a-ziyuan388"></use>
        </svg>
        <span>很抱歉，当前链接已失效</span>
        <div class="goback" @click="goBackLogin">返回</div>
      </div>
    </div>
  </div>

  <div v-if="loadMode == 4" class="ddei_sslink_enterpwd">
    <div class="content">
      <div class="header">
        <svg class="icon warn" aria-hidden="true">
          <use xlink:href="#icon-a-ziyuan378"></use>
        </svg>
        <span>请输入提取码</span>
      </div>
      <div class="field">
        <div class="link-code-title">提取码：</div>
        <div class="link-code">
          <input v-model="inputPwdCode" @keydown.enter="enterPwdCode">
        </div>
      </div>

      <div class="button" @click="enterPwdCode">确定</div>

    </div>
  </div>
</template>

<script lang="ts">
import { userinfo } from "@/lib/api/login/index.js";
import { loadfile, savefile, publishfile } from "@/lib/api/file";
import { shortlinklogin } from "@/lib/api/shortlink";
import Cookies from "js-cookie";
import DDeiEditorView from "ddei-editor";

import { debounce } from "lodash";
import { markRaw } from "vue";

import {DDeiEditorEnumBusCommandType} from "ddei-editor";
import { DDeiEditorUtil } from "ddei-editor";
import { DDeiEditor } from "ddei-editor";
import { DDei } from "ddei-editor";
import { DDeiUtil } from "ddei-editor";



//引入插件
import { DDeiCoreTopMenuPanel,DDeiCoreThemeBlack, DDeiCoreControls,DDeiCoreHotkeys,DDeiKeyActionAllSelect,DDeiCorePropertyViewPanel,DDeiCoreToolboxPanel,DDeiCoreSheetsPanel, DDeiCoreChangeRatioPanel, DDeiCoreChangeRatioDialog,DDeiCoreShapeCountPanel, DDeiCoreBottomMenuPanel,DDeiCoreStandLayout, DDeiCoreOpenFilesViewPanel, DDeiCoreQuickColorViewPanel, DDeiCoreAlignDialog } from "ddei-editor";
import {DDeiExtUML} from "ddei-editor"
import { DDeiCoreGoBackPanel } from "@ddei-ext/ext"
import DDeiExperience from "@ddei-ext/ext"
export default {
  props: {},
  data() {
    
    return {

      publishPostData: null,
      inputPwdCode: "",
      loadMode: 0,//加载模式0，不加载
     
      options: markRaw({
        config: {
          "mark": "水印文本",
          "grid": 2,
          "paper": { type: "A6", direct: 1 },
          // "paper":"A5",
          "ruler": true,
          // "background": { color: "#123456", opacity: 0.1 },
          // "theme": "ddei-core-theme-black",
          // initData: {
          //   controls: [
          //     {
          //       id: "act_1",
          //       model: "102010",
          //       code: "active_01",
          //       text: "第一步",
          //       border: { color: "yellow", dash: [10, 10, 5, 5], width: 5 },
          //       fill: { color: "grey" },
          //     },
          //     {
          //       id: "act_2",
          //       model: "102010",
          //       code: "active_02",
          //       width: 200,
          //       height: 100,
          //       text: "第二步",
          //       offsetY: -70,
          //     }
          //   ]
          // }
          EVENT_LOAD_FILE: this.openFile
        },
        //配置扩展插件
        extensions: [
          DDeiExperience,
          DDeiCoreTopMenuPanel.configuration({
            panels: [DDeiCoreGoBackPanel,"ddei-core-panel-fileinfo",
              "ddei-core-panel-operate", "ddei-core-panel-fontandtext", "ddei-core-panel-tool"
              , "ddei-core-panel-sort"]}),
          DDeiExtUML,
        ],
      })
    };
  },
  //注册组件
  components: {
    DDeiEditorView
  },
  created() {
    this.displayQuickDialog = debounce(this.displayQuickDialog, 200, { trailing: true, leading: false });
    window.onbeforeunload = this.beforeUnload;
  },
  beforeMount() {
    let routePath = decodeURIComponent(this.$route.path)
    if (routePath.startsWith("/ss/")) {
      //获取短链接码
      let ssUrl = routePath.substring(4)
      let pwdCode = ''
      //获取URL中的验证码
      if (ssUrl.indexOf("码") != -1) {
        pwdCode = ssUrl.substring(ssUrl.indexOf(":") + 1)
        ssUrl = ssUrl.substring(0, ssUrl.indexOf("提"))
      }
      //加载获取短链接信息
      this.makeShortLinkLogin(ssUrl, pwdCode)
    } else {
      this.loadMode = 1
    }
  },
  mounted() {
  },
  methods: {

    beforeUnload(e) {
      let files = this.editor?.files

      let hasDirty = false;
      for (let i = 0; i < files?.length; i++) {
        if (files[i].state != DDeiFileState.NONE) {
          hasDirty = true;
          break;
        }
      }
      if (hasDirty) {
        var e = window.event || e;
        e.returnValue = ("确定离开当前页面吗（未保存数据将会丢失）？");
      }
    },
    /**
     * 执行短链接登陆
     * @param ssUrl 
     * @param pwdCode 
     */
    makeShortLinkLogin(ssUrl, pwdCode) {
      shortlinklogin(ssUrl, pwdCode).then(ssResult => {
        if (ssResult.status == 200 && ssResult.data.code == 0 && ssResult.data.data) {
          // 缓存 token
          Cookies.set('token', ssResult.data.data.token)
          Cookies.set('refreshToken', ssResult.data.data.refreshToken)
          Cookies.set('tokenExp', ssResult.data.data.tokenExp)
          this.ssUrl = ssUrl
          this.getUserInfo().then(result => {
            let loadMode = 1
            if (result) {
              let userCookie = Cookies.get("user");
              if (userCookie) {
                let user = JSON.parse(userCookie)
                let sslink
                for (let i = 0; i < user?.sslinks?.length; i++) {
                  if (user.sslinks[i].url == this.ssUrl) {
                    sslink = user.sslinks[i]
                    break;
                  }
                }
                if (sslink?.state == 1) {
                  loadMode = 2
                } else if (sslink) {
                  //校验是否过期、是否输入了验证码等信息
                  if (sslink.end_type != 99) {
                    let nowTimeStr = DDeiUtil.formatDate(new Date(), "yyyy-MM-ddThh:MM:ss")
                    if (nowTimeStr >= sslink.end_time) {
                      loadMode = 3//超期
                    }
                  }
                  if (loadMode != 3 && sslink.state == 0) {
                    loadMode = 4//未输入验证码，要求输入验证码
                  }
                }
              }
            }
            this.loadMode = loadMode
          })
        } else {
          this.loadMode = 1
        }
      })
    },

    enterPwdCode() {
      this.makeShortLinkLogin(this.ssUrl, this.inputPwdCode)
    },
    /**
     * 查看前
     */
    viewBefore(operate, models, propName, ddInstance, evt) {
      models.forEach((model) => {
        console.log(
          "查看前:" + model.id + " 属性——" + propName + " .  " + model[propName]
        );
      });
      return true;
    },
    /**
     * 查看后
     */
    viewAfter(operate, models, propName, ddInstance, evt) {
      models.forEach((model) => {
        console.log(
          "查看:" + model.id + " 属性——" + propName + " .  " + model[propName]
        );
      });
    },
    /**
     * 编辑值前
     */
    editBefore(operate, models, propName, ddInstance, evt) {
      models.forEach((model) => {
        console.log(
          "准备编辑:" +
          model.id +
          " 属性——" +
          propName +
          " .  " +
          model[propName]
        );
      });
      return true;
    },
    /**
     * 编辑值后
     */
    editAfter(operate, models, propName, ddInstance, evt) {
      models.forEach((model) => {
        console.log(
          "编辑:" + model.id + " 属性——" + propName + " .  " + model[propName]
        );
      });
    },
    /**
     * 删除后
     */
    removeAfter(operate, models, propName, ddInstance, evt) {
      models.forEach((model) => {
        console.log("删除:" + model.id);
      });
    },


    /**
     * 选择前
     */
    selectBefore() {
      console.log("选择前");
      return true;
    },

    /**
     * 选择后，在选择控件的合适位置显示快捷编辑框
     */
    showQuickEditPicker(operateType, models, propName, ddInstance, evt) {
      if (ddInstance && ddInstance["AC_DESIGN_EDIT"]) {
        let editor = DDeiEditorCls.ACTIVE_INSTANCE;
        let curState = editor.state
        //隐藏弹出框
        DDeiEditorUtil.closeDialog('ddei-core-dialog-quickpop')

        //显示弹出框
        if (models?.length > 0) {
          let height = 100;
          //计算弹出框的显示位置，这里需要把模型的坐标转换为dom的坐标
          let modelPos = DDeiUtil.getModelsDomAbsPosition(models)
          let left = modelPos.left + (modelPos.width / 2)
          let top = modelPos.top + (modelPos.height / 2)
          if (modelPos.top - height <= modelPos.cTop) {
            if (modelPos.height > 400) {
              top = top + height + 20
            } else {
              top = top + modelPos.height / 2 + 20;
            }
          } else {
            top = top - height;
          }
          if (top < 0) {
            top = modelPos.cTop + modelPos.cHeight / 2
          }

          if (left < 0) {
            left = 0
          }
          DDeiEditorUtil.showDialog('ddei-core-dialog-quickpop', {
            group: "canvas-pop"
          }, { type: 99, left: left, top: top, hiddenMask: true }, null, true, true)
          editor?.changeState(curState)
        }
      }
    },
    /**
     * 打开文件
     */
    async openFile(isReExec) {
      this.serverFunc = this.openFile
      this.serverFuncParam = 1
      if (isReExec) {
       
        let ddInstance = this.$refs.editorViewer.editor.ddInstance
        ddInstance.bus.push(DDeiEditorEnumBusCommandType.LoadFile)
        ddInstance.bus.executeAll();
      } else if (await this.getUserInfo(this.ssUrl)) {
        //普通文件打开
        let loadFileJSON = {}
        if (this.loadMode == 1) {
          //获取参数
          let fileId = this.$route.params.id;
          loadFileJSON.id = fileId
        } else if (this.loadMode == 2) {
          //获取参数
          let userCookie = Cookies.get("user");
          let user = JSON.parse(userCookie)
          let sslink
          for (let i = 0; i < user.sslinks?.length; i++) {
            if (user.sslinks[i].url == this.ssUrl) {
              sslink = user.sslinks[i]
              break;
            }
          }
          loadFileJSON.fv_id = sslink.fv_id
        }

        //根据ID获取文件的设计以及文件的信息
        let fileData = await loadfile(loadFileJSON);
        if (fileData.status == 200) {
          if (fileData.data.code == 0) {
            let returnData = fileData.data.data;
            //保存的业务ID
            returnData.extData = { busiid: "busi_" + returnData.id, owner: returnData.owner };
            let busiData = await this.loadBusiData();
            returnData.busiData = busiData;
            //加载业务信息，以用于显示填充数据
            return returnData;
          }
        }

      }



    },

    /**
     * 加载业务数据
     */
    async loadBusiData() {
      //加载业务数据并返回
      return {
        签名: "hoslay",
        签名64:
          "",
        签名URL: "https://www.baidu.com/img/flexible/logo/pc/result@2.png",
        日期: new Date().getTime(),
        发起人: "张三",
        类型: "差旅费报销",
        总金额: 23112.25,
        流程: [
          {
            名称: "发起",
            处理人: "张三",
            处理时间: "2023-01-01 23:12:12",
          },
          {
            名称: "审批",
            处理人: "李四",
            处理时间: "2023-01-02 09:13:13",
            意见: "同意",
          },
          {
            名称: "支付",
            处理人: "王五",
            处理时间: "2023-01-03 17:17:00",
            意见: "已打款至账户",
          },
          {
            名称: "办结",
            处理时间: "2023-01-03 17:17:00",
          },
        ],
        单据: [
          {
            开始日期: "12-15",
            结束日期: "12-15",
            餐费: 20,
            交通费: 36,
            备注: "07:35-21:30",
          },
          {
            开始日期: "12-16",
            结束日期: "12-16",
            餐费: 20,
            交通费: 37,
            备注: "09:00-23:00",
          },
          {
            开始日期: "12-17",
            结束日期: "12-17",
            餐费: 20,
            交通费: 40,
            备注: "09:00-22:00,送同事",
          },
          {
            开始日期: "12-18",
            结束日期: "12-18",
            餐费: 20,
            交通费: 35,
            备注: "08:30-21:30",
          },
          {
            开始日期: "12-19",
            结束日期: "12-20",
            餐费: 26,
            交通费: 30,
            备注: "09:00-00:00",
          },
          {
            开始日期: "12-21",
            结束日期: "12-21",
            餐费: 40,
            交通费: 38,
            备注: "09:00-23:00",
          },
        ],
      };
    },

    /**
     * 保存文件以及设计
     */
    async saveFile(designdata, file) {
      //根据ID获取文件的设计以及文件的信息
      if (designdata) {

        if (designdata.id && file.local != 1) {
          let postData = {
            id: designdata.id,
            name: designdata.name,
            code: designdata.code,
            desc: designdata.desc,
            thumb: designdata.thumb,
          };
          //删除提交数据中的缩略图
          delete designdata.thumb
          postData.content = JSON.stringify(designdata)
          if (await this.getUserInfo()) {
            let fileData = await savefile(postData);
            if (fileData.status == 200) {
              if (fileData.data.code == 0) {
                return { result: 1, msg: "" };
              } else {
                return { result: 2, msg: "保存失败" };
              }
            }
          } else {
            return { result: 2, msg: "保存失败" };
          }
        }
        //保存到本地还是服务器
        else {
          if (!file.localFileHandler) {
            file.localFileHandler = await showSaveFilePicker({
              description: "DDei Design File",
              suggestedName: designdata.name + ".dei",
              types: [{
                accept: {
                  "text/plain": [".dei"]
                }
              }]
            });
          }
          delete designdata.thumb
          file.local = 1
          await file.writeLocalFile(JSON.stringify(designdata))
          return { result: 1, msg: "" };
        }

      }
    },

    reExecFunc() {
      if (this.serverFunc) {
        this.serverFunc(this.serverFuncParam)
        delete this.serverFunc
        delete this.serverFuncParam
      } else {
        let ddInstance = this.$refs.editorViewer.editor.ddInstance
        ddInstance.bus.restoreQueue();
        ddInstance.bus.executeAll();
      }
    },

    /**
     * 保存文件以及设计并发布文件
     */
    async publishFile(designdata) {
      if (await this.getUserInfo()) {
        //根据ID获取文件的设计以及文件的信息
        this.publishPostData = null;
        if (designdata) {
          let postData = {
            id: designdata.id,
            name: designdata.name,
            code: designdata.code,
            desc: designdata.desc,
            version: designdata.version,
            thumb: designdata.thumb
          };
          //删除提交数据中的缩略图
          delete designdata.thumb
          postData.content = JSON.stringify(designdata)
          this.publishPostData = Object.freeze(postData);
          //缓存数据，弹出确认框进行确认
          this.showPublishFileDialog();
          //等待弹出框确认
          let dialogResult = await this.waitingPublishDialog();
          if (dialogResult == 1) {
            if (this.publishPostData) {
              let fileData = await publishfile(this.publishPostData);
              if (fileData.status == 200) {
                if (fileData.data.code == 0) {
                  return { result: 1, msg: "" };
                } else {
                  return { result: 2, msg: "发布失败" };
                }
              }
            }
          } else {
            return { result: 3, msg: "发布取消" };
          }
        } else {
          return { result: 2, msg: "发布失败" };
        }
      }
    },

    /**
     * 等待弹框确认
     */
    async waitingPublishDialog() {
      this.publishDialogState = 0;
      while (this.publishDialogState == 0) {
        await new Promise((resolve) => setTimeout(resolve, 10));
      }
      return this.publishDialogState;
    },

    /**
     * 正在进行鼠标操作
     */
    mouseOperating(operateType, models, ddInstance, evt) {
      if (ddInstance && ddInstance["AC_DESIGN_EDIT"]) {
        DDeiEditorUtil.hiddenDialog('ddei-core-dialog-quickpop')
        if (operateType == "CHANGE_RATIO" || operateType == "CHANGE_WPV" || operateType == "CHANGE_BOUNDS" || operateType == "CHANGE_ROTATE") {
          this.displayQuickDialog();
        }
      }
    },

    /**
     * 拖拽前
     */
    dragBefore(operate, models, propName, ddInstance, evt) {
      if (DDei.beforeOperateValid(operate, models, propName, ddInstance, evt)) {
        if (ddInstance && ddInstance["AC_DESIGN_EDIT"]) {
          DDeiEditorUtil.hiddenDialog('ddei-core-dialog-quickpop')
        }
        return true
      }
      return false
    },

    /**
     * 拖拽线节点前
     */
    dragLineBefore(operate, dragObj, ddInstance, evt) {
      if (DDei.beforeOperateValid(operate, [dragObj?.model], null, ddInstance, evt)) {
        if (ddInstance && ddInstance["AC_DESIGN_EDIT"]) {
          DDeiEditorUtil.hiddenDialog('ddei-core-dialog-quickpop')
        }
        return true
      }
      return false
    },



    /**
     * 移动滚动条
     */
    changeWPV(oldValue, newValue, ddInstance) {
      if (ddInstance && ddInstance["AC_DESIGN_EDIT"]) {
        DDeiEditorUtil.hiddenDialog('ddei-core-dialog-quickpop')
        this.displayQuickDialog();
      }
    },

    displayQuickDialog() {
      let editor = DDeiEditorCls.ACTIVE_INSTANCE;
      if (editor?.ddInstance?.stage?.selectedModels?.size > 0) {
        let models = Array.from(editor.ddInstance.stage?.selectedModels.values())
        if (models?.length > 0) {
          let height = 100;
          //计算弹出框的显示位置，这里需要把模型的坐标转换为dom的坐标
          let modelPos = DDeiUtil.getModelsDomAbsPosition(models)
          let left = modelPos.left + 20
          let top = modelPos.top
          if (modelPos.top - height <= modelPos.cTop) {
            if (modelPos.height > 400) {
              top = top + height + 20
            } else {
              top = top + modelPos.height + 20;
            }
          } else {
            top = top - height;
          }
          if (top < 0) {
            top = modelPos.cTop + modelPos.cHeight / 2
          }
          if (left < 0) {
            left = 0
          }


          DDeiEditorUtil.displayDialog('ddei-core-dialog-quickpop', null, { type: 99, left: left, top: top, hiddenMask: true })
        }
      }
    },

    /**
     * 改变缩放大小
     */
    changeRatio(oldValue, newValue, ddInstance) {
      if (ddInstance && ddInstance["AC_DESIGN_EDIT"]) {
        DDeiEditorUtil.hiddenDialog('ddei-core-dialog-quickpop')
        this.displayQuickDialog();
      }
    },

    /**
     * 确认发布文件
     */
    submitPublishFile() {
      this.publishDialogState = 1;
    },
    /**
     * 取消发布文件
     */
    cancelPublishFile() {
      this.publishDialogState = 2;
    },

    

    goBackLogin() {
      Cookies.remove("token");
      Cookies.remove("user");
      this.$router.push({
        path: "/login",
      });
    },

    /**
     * 弹出发布文件弹出框
     */
    showPublishFileDialog() {
      DDeiEditorUtil.showDialog("ddei-core-dialog-publishfile", {
        msg: '是否发布"' + this.publishPostData?.name + ' V' + this.publishPostData?.version + '"？',
        callback: {
          cancel: this.cancelPublishFile,
          ok: this.submitPublishFile,
        },
        background: "white",
        opacity: "1%",
        event: -1
      })
    },
    /**
     * 获取登录用户信息
     */
    async getUserInfo() {
      try {
        let response = await userinfo(this.ssUrl)
        let userJSON = response.data.data;
        let user = JSON.stringify(userJSON, null, 4);
        Cookies.set("user", user);
        return true;
      } catch (e) {
        Cookies.remove("token");
        //弹出登录弹出框
        DDeiEditorUtil.showDialog("ddei-core-dialog-relogin", {
          icon: "#icon-a-ziyuan411",
          msg: "当前登录状态已失效，请重新登录.",
          callback: {
            abort: this.clearServerFunc,
            ok: this.reExecFunc
          },
          background: "white",
          opacity: "1%",
          event: -1
        })
        return false;
      };
    },


    clearServerFunc() {
      delete this.serverFunc
      delete this.serverFuncParam
    },
    toLogin() {
      this.$router.push({
        path: this.$route.query.redirect || "/login",
      });
    }
  },
};
</script>
<style lang="less" scoped>
/* .删除文件弹框 */
.publish_file_dialog {
  z-index: 99;
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  height: calc(100vh);

  .content {
    position: absolute;
    width: 300px;
    height: 180px;
    left: calc(50% - 150px);
    top: calc(50% - 90px);
    background: #fff;
    border-radius: 10px;
    text-align: center;
    font-size: 17px;
    color: black;

    .title {
      width: 100%;
      font-size: 20px;
      color: #3662ec;
      text-align: center;
      margin-top: 15px;
    }

    .content_input {
      width: 80%;
      height: 30px;
      font-size: 18px;
    }

    .msg {
      width: 100%;
      height: 20px;
      font-size: 12px;
      color: red;
      text-align: right;
      padding-right: 30px;
    }

    .buttons {
      width: 80%;
      display: block;
      margin: auto;

      >div {
        width: 45%;
        height: 40px;
        cursor: pointer;
        cursor: pointer;
        border-radius: 2px;
        text-align: center;
        padding-top: 6px;

        >span {
          font-size: 15px;
          color: white;
          text-align: center;
          pointer-events: none;
        }
      }

      .button_ok {
        background-color: #3662ec;
        border-color: #3662ec;
        float: left;
      }

      .button_cancel {
        background-color: rgb(210, 210, 210);
        border-color: rgb(210, 210, 210);
        float: right;
      }
    }
  }
}

/**以下为询问框的样式 */
.ddei_sslink_outtime {
  width: 100%;
  height: calc(100vh);
  color: black;
  background: #FFFFFF;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;

  .content {
    display: flex;
    flex-direction: column;

    .header {
      flex: 0 0 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22px;
      font-family: "Microsoft YaHei";
      font-weight: 400;
      margin-top: 10px;
      color: #000000;

      .icon {
        font-size: 30px;
        margin-right: 10px;
      }

      .goback {
        margin-left: 10px;
        cursor: pointer;
        text-decoration: underline;
      }
    }
  }
}



.ddei_sslink_enterpwd {
  width: 100%;
  height: calc(100vh);
  color: black;
  background: #FFFFFF;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;

  .content {
    border: 2px solid #176EFF;
    border-radius: 4px;
    width: 420px;
    height: 200px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 0 24px;

    .header {
      flex: 0 0 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22px;
      font-family: "Microsoft YaHei";
      font-weight: 400;
      margin-top: 10px;
      color: #000000;

      .icon {
        font-size: 30px;
      }



    }


    .field {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      user-select: none;


      .link-code-title {
        flex: 0 0 100px;
        height: 30px;
        padding-left: 10px;
        text-align: left;
        font-size: 20px;
      }


      .link-code {
        flex: 0 0 120px;
        border: 1px solid #176EFF;
        border-radius: 4px;
        height: 50px;
        display: flex;
        justify-content: center;
        align-items: center;

        >input {
          flex: 0 0 80px;
          outline: none;
          background: none;
          border: none;
          width: 80px;
          font-size: 20px;
        }
      }
    }

    .button {
      width: 200px;
      height: 40px;
      background: #FFFFFF;
      border: 1px solid var(--panel-border);
      border-radius: 6px;
      font-size: 20px;
      font-family: "Microsoft YaHei";
      font-weight: 400;
      color: #040404;
      margin-left: 13px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      background: #176EFF;
      margin-bottom: 10px;

    }

    .button:hover {
      cursor: pointer;
    }

  }



}
</style>
